package com.vitech.javacertification.threads.hungrybirds;
class MotherBird extends Thread {
	
	private WormsDish wormDish;
	private boolean babyCrying = false;
	private int numberofWormscaptured = 10;
	
	public MotherBird (WormsDish wormDish) {
		this.wormDish = wormDish;
	}
	
	public synchronized void babyStarving (BabyBird myBaby) {
		babyCrying = true;
		System.out.println("\n"+ getTime() + " " + myBaby.getName()+" baby crying");
		notify();
	}
	
	public synchronized void run () {
		while(true){
			if (!babyCrying){
				
				try {
					System.out.println("babies quiet, so rest until a notify comes");				
					wait();
					System.out.println("Mother waking up");
					
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			// baby started crying
			int numberofWormscaptured = 0;
			while (numberofWormscaptured == 0){
				numberofWormscaptured = (int) (Math.random () * 10);					
			}
			System.out.println("Adding " +numberofWormscaptured + " worms");
			
			try {
				
				this.wait(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			wormDish.parentAddsWorm (numberofWormscaptured);
			
			this.babyCrying = false;
			try {
				System.out.println("\n"+ getTime() +"\nSleeping\n");
				sleep(10000);
				System.out.println("\n"+ getTime() +"\nWaking\n");
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	
	int getTime(){
	
		return ((int) System.currentTimeMillis())/1000;
	}
}

